import { loginPassword, logout, userInfo } from '@/api/mivawork/user.js';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { resetRouter } from '@/router';
import { Message } from 'element-ui';

const state = {
  token: getToken(),
  nickname: '',
  avatar: '',
  introduction: '',
  roles: []
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, nickname) => {
    state.nickname = nickname;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    console.log(userInfo);
    const { phone, email, verifyCode, password } = userInfo;
    return new Promise((resolve, reject) => {
      loginPassword({ phone, email, verifyCode, password }).then(response => {
        if (response.code !== 200) {
          reject(response.message);
        }
        commit('SET_TOKEN', response.data);
        setToken(response.data);
        resolve(response);
      }).catch(error => {
        reject(error);
      });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      userInfo(state.token).then(response => {
        const { data } = response;

        if (!data) {
          reject('验证失败，请重新登录.');
        }

        if (data.user_account_roles.length === 0) {
          reject('你不是管理员不能进来 (｀・ω・´) ');
        }

        const { nickname, avatar, user_account_roles } = data;
        const reRoles = ['米米法'];
        for (const val of user_account_roles) {
          reRoles.push(val.role_name);
        }
        commit('SET_NAME', nickname);
        commit('SET_AVATAR', avatar);
        commit('SET_ROLES', reRoles);
        resolve(data);
      }).catch(error => {
        reject(error);
      });
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '');
        commit('SET_ROLES', []);
        removeToken();
        resetRouter();

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true });

        resolve();
      }).catch(error => {
        reject(error);
      });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      removeToken();
      resolve();
    });
  }

};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};

